package com.ppyydd.sms.utils;

import org.dom4j.Document;
import org.dom4j.io.SAXReader;

import java.sql.*;

public class JdbcUtils {
    private static String user;
    private static String password;
    private static String port;
    private static String host;
    private static String databases;
    private static Connection connection = null;

    //加载DB驱动
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read("E:/java/project/smss/conf/database.xml");
            host = document.selectSingleNode("/properties/property[@current='1']/host/text()").getStringValue();
            password = document.selectSingleNode("/properties/property[@current='1']/password/text()").getStringValue();
            port = document.selectSingleNode("/properties/property[@current='1']/port/text()").getStringValue();
            user = document.selectSingleNode("/properties/property[@current='1']/username/text()").getStringValue();
            databases = document.selectSingleNode("/properties/property[@current='1']/database/text()").getStringValue();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取Connection对象
    public static Connection getConnection() throws SQLException {
        String url = "jdbc:mysql://" + host + ":" + port + "/" + databases + "?characterEncoding=utf-8";
        Connection connection = null;
        if (connection == null) {
            connection = DriverManager.getConnection(url, user, password);
        }
        return connection;
    }

    //关闭资源
    public static void close(Connection con, Statement stmt, ResultSet rs, PreparedStatement pstmt) throws SQLException {
        if (rs != null) {
            rs.close();
            rs = null;
        }
        if (pstmt != null) {
            pstmt.close();
            pstmt = null;
        }
        if (stmt != null && !stmt.isClosed()) {
            stmt.close();
            stmt = null;
        }
        if (con != null && !con.isClosed()) {
            con.close();
            con = null;
        }
    }
}
